package com.example.ymm.modules1.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.my.user.*;
import com.example.ymm.modules1.mapper.my.user.DbOrderMapper;
import com.example.ymm.modules1.query.DbOrderItemQueryCriteria;
import com.example.ymm.modules1.query.DbOrderQueryCriteria;
import com.example.ymm.modules1.service.dd.DingMiniNoticeService;
import com.example.ymm.modules1.service.dto.SysRankingQueryCriteria;
import com.example.ymm.modules1.service.user.*;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DbOrderServiceImpl extends BaseServiceImpl<DbOrderMapper, DbOrder> implements DbOrderService {

    @Autowired
    DbOrderItemService dbOrderItemService;
    @Autowired
    DbGoodService dbGoodService;
    @Autowired
    DbUserService dbUserService;
    @Autowired
    DbIntegralLogService dbIntegralLogService;

    @Autowired
    DingMiniNoticeService dingMiniNoticeService;

    @Override
    public TableList<DbOrder> list(DbOrderQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbOrder> page = new Page<DbOrder>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbOrder.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<DbOrder> tableList=new TableList(page);
        List<DbOrder> list = tableList.getList();
        list.forEach(r->{
            DbOrderItemQueryCriteria itemQueryCriteria=new DbOrderItemQueryCriteria();
            itemQueryCriteria.setOrderId(r.getOrderId());
            List<DbOrderItem> dbOrderItems = dbOrderItemService.queryAll(itemQueryCriteria);
            r.setItems(dbOrderItems);
        });
        return tableList;
    }

    public List<DbOrder> queryAll(DbOrderQueryCriteria criteria) {
        List<DbOrder> result =baseMapper.selectList(QueryHelpPlus.getPredicate(DbOrder.class, criteria));
        return result;
    }

    @Override
    public DbOrder orderCancel(String orderId) {
        DbOrder order = getById(orderId);
        order.setStatus(99);
        saveOrUpdate(order);

        String userId = order.getUserId();
        DbUser user = dbUserService.getById(userId);
        user.setIntegral(user.getIntegral()+order.getIntegral());
        dbUserService.saveOrUpdate(user);

        DbIntegralLog integralLog=new DbIntegralLog();
        integralLog.setIntegral(order.getIntegral());
        integralLog.setUserId(userId);
        integralLog.setUserName(user.getUserName());
        integralLog.setNote("取消订单退还积分");
        integralLog.setType(1);
        integralLog.setOrderId(order.getOrderId());
        dbIntegralLogService.saveOrUpdate(integralLog);

        try{
            dingMiniNoticeService.sendIntegralCancelOrderMsg(integralLog);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }


        return order;
    }


    @Override
    public List<DbOrder> getOneHourOrderList(DbOrderQueryCriteria criteria) {
        return baseMapper.getOneHourOrderList(criteria);
    }

    @Override
    public DbOrder userOrderCancel(String orderId) {
        DbOrder order = getById(orderId);

        //对比下单时间看是否超过3个小时，3个小时无法取消
        Date create_date = order.getCreateTime();
        Date compare_date = DateKit.dateAdd(5, create_date, 3);
        Date now=new Date();
        if(now.after(compare_date)){
            throw new YmException("您的订单已超过3个小时，已无法取消订单，人事正在准备订单中!");
        }else{
            System.out.println("可以取消");
        }
        if(order.getStatus()==2){
            throw new YmException("该订单人事行政正在准备中无法取消!");

        }

        order.setStatus(99);
        saveOrUpdate(order);

        String userId = order.getUserId();
        DbUser user = dbUserService.getById(userId);
        user.setIntegral(user.getIntegral()+order.getIntegral());
        dbUserService.saveOrUpdate(user);

        DbIntegralLog integralLog=new DbIntegralLog();
        integralLog.setIntegral(order.getIntegral());
        integralLog.setUserId(userId);
        integralLog.setUserName(user.getUserName());
        integralLog.setNote("取消订单退还积分");
        integralLog.setType(1);
        integralLog.setOrderId(order.getOrderId());
        dbIntegralLogService.saveOrUpdate(integralLog);
        return order;
    }

    @Override
    public DbOrder takesOrder(String orderId) {
        DbOrder order = getById(orderId);
        order.setStatus(1);
        saveOrUpdate(order);
        DbOrderItemQueryCriteria itemQueryCriteria=new DbOrderItemQueryCriteria();
        itemQueryCriteria.setOrderId(orderId);
        List<DbOrderItem> dbOrderItems = dbOrderItemService.queryAll(itemQueryCriteria);
        //扣库存
        dbOrderItems.forEach(r->{
            DbGood good = dbGoodService.getById(r.getGoodId());
            if(UtilValidate.isNotEmpty(good)){
                good.setStock(good.getStock()-r.getNum());
                dbGoodService.saveOrUpdate(good);
            }
        });
        return order;
    }

    @Override
    public DbOrder detail(String orderId) {
        DbOrder order = getById(orderId);
        DbOrderItemQueryCriteria itemQueryCriteria=new DbOrderItemQueryCriteria();
        itemQueryCriteria.setOrderId(orderId);
        List<DbOrderItem> dbOrderItems = dbOrderItemService.queryAll(itemQueryCriteria);
        order.setItems(dbOrderItems);
        return order;
    }


    @Override
    public void syncLockOrders() {
        DbOrderQueryCriteria criteria=new DbOrderQueryCriteria();
        criteria.setStatus(0);
        List<DbOrder> oneHourOrderList = getOneHourOrderList(criteria);
        oneHourOrderList.forEach(r->{
            r.setStatus(2);
            dingMiniNoticeService.OATempleNotice(r);
        });
        saveOrUpdateBatch(oneHourOrderList);

    }

    @Override
    public DbOrder buyNow(DbOrderItem dbOrderItem) {
        if(UtilValidate.isEmpty(dbOrderItem.getGoodId())){
            throw new YmException("缺少商品");
        }
        DbGood good = dbGoodService.getById(dbOrderItem.getGoodId());
        String userId = getUserId();
        DbUser user = dbUserService.getById(userId);
        if(user.getIntegral()<good.getIntegral()){
            throw new YmException("积分不足哦！");
        }
        user.setIntegral(user.getIntegral()-good.getIntegral());
        dbUserService.saveOrUpdate(user);
//        good.setStock(good.getStock()-1);
//        dbGoodService.saveOrUpdate(good);



        DbOrder order=new DbOrder();
        order.setStatus(0);
        order.setIntegral(good.getIntegral());
        order.setUserId(userId);
        order.setUserName(user.getUserName());
        order.setNum(1);
        saveOrUpdate(order);

        DbOrderItem orderItem=new DbOrderItem();
        orderItem.setOrderId(order.getOrderId());
        orderItem.setIntegral(good.getIntegral());
        orderItem.setNum(1);
        orderItem.setGoodId(good.getGoodId());
        orderItem.setGoodName(good.getGoodName());
        String mainImg = good.getMainImg();
        String img=null;
        if(UtilValidate.isNotEmpty(mainImg)){
            String[] split = mainImg.split(",");
            img=split[0];
        }
        orderItem.setMainImg(img);
        dbOrderItemService.saveOrUpdate(orderItem);

        DbIntegralLog integralLog=new DbIntegralLog();
        integralLog.setIntegral(good.getIntegral());
        integralLog.setUserId(userId);
        integralLog.setUserName(user.getUserName());
        integralLog.setNote("兑换商品扣除积分");
        integralLog.setType(2);
        integralLog.setOrderId(order.getOrderId());
        dbIntegralLogService.saveOrUpdate(integralLog);

        return order;
    }


    @Override
    public Integer orderNumCount(SysRankingQueryCriteria criteria) {
        return baseMapper.orderNumCount(criteria);
    }


    @Override
    public Double totalConversionIntegral(SysRankingQueryCriteria criteria) {
        List<Integer> statusIns=new ArrayList<>();
        statusIns.add(1);
        statusIns.add(2);
        criteria.setStatusIns(statusIns);
        Double aDouble = baseMapper.totalConversionIntegral(criteria);
        return aDouble;
    }
}
